<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工序编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入工序编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工序名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入工序名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工序类型" prop="typeId">
        <treeselect
          v-model="queryParams.typeId"
          :options="typeOptions"
          :normalizer="normalizer"
          placeholder="请选择工序类型"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="正常" value="1"></el-option>
          <el-option label="停用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['qep:process:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qep:process:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qep:process:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['qep:process:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="processList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工序编号" align="center" prop="code" />
      <el-table-column label="工序名称" align="center" prop="name" />
      <el-table-column label="工序类型" align="center" prop="typeName" />
      <el-table-column label="工序描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="标准工时(分钟)" align="center" prop="standardTime" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="danger">停用</el-tag>
          <el-tag v-else type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qep:process:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Setting"
            @click="handleParams(scope.row)"
            v-hasPermi="['qep:process:list']"
          >参数配置</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qep:process:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产工序对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="工序编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入工序编号" />
        </el-form-item>
        <el-form-item label="工序名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入工序名称" />
        </el-form-item>
        <el-form-item label="工序类型" prop="typeId">
          <treeselect
            v-model="form.typeId"
            :options="typeOptions"
            :normalizer="normalizer"
            placeholder="请选择工序类型"
          />
        </el-form-item>
        <el-form-item label="工序描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入工序描述" />
        </el-form-item>
        <el-form-item label="标准工时" prop="standardTime">
          <el-input-number v-model="form.standardTime" controls-position="right" :min="0" :precision="2" placeholder="请输入标准工时(分钟)" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listProcess, getProcess, delProcess, addProcess, updateProcess, exportProcess } from "@/api/qep/process";
import { listProcessTypeTree } from "@/api/qep/processType";
import Treeselect from "vue3-treeselect";
import "vue3-treeselect/dist/vue3-treeselect.css";
import { parseTime } from '@/utils/ruoyi';
import { ref, toRefs, reactive } from 'vue';

export default {
  name: "Process",
  dicts: ['sys_normal_disable'],
  components: { Treeselect },
  setup() {
    const queryForm = ref(null);
    const form = ref(null);
  
    return {
      queryForm,
      form,
      parseTime
    };
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产工序表格数据
      processList: [],
      // 工序类型树选项
      typeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: undefined,
        name: undefined,
        typeId: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "工序编号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "工序名称不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "工序类型不能为空", trigger: "blur" }
        ],
        standardTime: [
          { required: true, message: "标准工时不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getTypeTree();
  },
  methods: {
    parseTime,
    /** 查询生产工序列表 */
    getList() {
      this.loading = true;
      listProcess(this.queryParams).then(response => {
        this.processList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error("获取工序列表失败:", error);
        this.loading = false;
      });
    },
    /** 查询工序类型下拉树结构 */
    getTypeTree() {
      listProcessTypeTree().then(response => {
        this.typeOptions = [];
        const data = { id: 0, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.typeOptions.push(data);
      }).catch(error => {
        console.error("获取工序类型树失败:", error);
      });
    },
    /** 转换工序类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        name: null,
        typeId: null,
        description: null,
        standardTime: 0,
        status: 1,
        remark: null
      };
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      if (this.$refs.queryForm) {
        this.$refs.queryForm.resetFields();
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产工序";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProcess(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改生产工序";
      }).catch(error => {
        console.error("获取工序详情失败:", error);
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.$refs.form) {
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateProcess(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).catch(error => {
                console.error("更新工序失败:", error);
              });
            } else {
              addProcess(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).catch(error => {
                console.error("添加工序失败:", error);
              });
            }
          }
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除生产工序编号为"' + ids + '"的数据项?').then(function() {
        return delProcess(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch((error) => {
        if (error !== 'cancel') console.error("删除工序失败:", error);
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有工序数据?').then(() => {
        return exportProcess(this.queryParams);
      }).then(response => {
        this.$download.excel(response, `工序数据_${new Date().getTime()}.xlsx`);
      }).catch(() => {});
    },
    /** 处理树形数据结构 */
    handleTree(data, id, parentId) {
      let config = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: 'children'
      };

      var childrenListMap = {};
      var nodeIds = {};
      var tree = [];

      for (let d of data) {
        let parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
          childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
      }

      for (let d of data) {
        let parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
          tree.push(d);
        }
      }

      for (let t of tree) {
        adaptToChildrenList(t);
      }

      function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
          o[config.childrenList] = childrenListMap[o[config.id]];
        }
        if (o[config.childrenList]) {
          for (let c of o[config.childrenList]) {
            adaptToChildrenList(c);
          }
        }
      }
      return tree;
    },
    /** 参数配置按钮操作 */
    handleParams(row) {
      const processId = row.id;
      this.$router.push({ path: '/process/params', query: { processId: processId } });
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 